package com.yuyang.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yuyang.common.constant.AuthServerConstants;
import com.yuyang.common.utils.HttpUtils;
import com.yuyang.common.utils.R;
import com.yuyang.common.vo.MemberResponseVo;
import com.yuyang.gulimall.auth.feign.MemberFeignServer;
import com.yuyang.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import javax.swing.text.html.parser.Entity;
import java.util.HashMap;

/**
 * @author yu yang
 * @date 2023/1/29 -19:39
 */
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignServer memberFeignServer;
    @GetMapping("/oauth2.0/weibo")
    public String weibo(@RequestParam("code")String code, HttpSession session) throws Exception {
        //根据用户授权返回的code换取access_token
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","3691205142");
        map.put("client_secret","e8d683a0d9ac5abe5bb260de937dac8e");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo");
        map.put("code",code);

            HttpResponse httpResponse = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "POST", new HashMap<>(), new HashMap<>(), map);
            if (httpResponse.getStatusLine().getStatusCode() == 200){
                SocialUser socialUser = JSON.parseObject(EntityUtils.toString(httpResponse.getEntity()), SocialUser.class);
                //登录或者注册这个社交用户
                R r = memberFeignServer.weiboLogin(socialUser);
                if (r.getCode() == 0){
                    MemberResponseVo data = r.getData("data", new TypeReference<MemberResponseVo>() {
                    });
                    //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                    //以后浏览器访问哪个网站就会带上这个网站的cookie
                    //TODO 1、默认发的令牌。当前域（解决子域session共享问题）
                    //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                    session.setAttribute(AuthServerConstants.LOGIN_USER,data);

                    //2、登录成功跳回首页
                    return "redirect:http://gulimall.com";
                }else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }

    }

}
